<template>
	<div>
		<div>{{ count1 }}</div>
		<div>{{ count2 }}</div>
		<button @click="add">add</button>
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, reactive, toRefs } from 'vue';

export default defineComponent({
	setup() {
		const count1 = ref(0);
		const state = reactive({
			count2: 0,
		});

		const add = () => {
			count1.value += 1;
			state.count2 += 2;
		};

		// 1.监听整个reactive对象，
		// 2.监听单个属性，需要如下写成函数 () => state.count2
		const stop = watch(
			[count1, () => state.count2],
			(newVal, oldVal) => {
				console.log(newVal, oldVal);
				if (count1.value === 2) {
					stop();
				}
			},
			{
				// deep: true,
				// immediate: true, // 立马执行一次
				// flush: 'pre', // pre 组件更新前调用，sync 同步执行，post 组件更新后执行
			}
		);

		return {
			...toRefs(state),
			count1,
			add,
		};
	},
});
</script>

<style scoped></style>
